package cs2340.flyingkiwi.todoapp;

import android.app.ListActivity;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Paint;
import android.os.Bundle;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.Button;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;

/**
 * This class simulates an individual category.
 * 
 * @author Group Flying Kiwi
 * @version 30 Mar 2012
 * 
 * It extends ListActivity class to show all the items category has.
 * Methods used in here are very similar to the methods in AccountManager class.
 */

public class Category extends ListActivity{
	
	private String accountId;
	private String categoryId;
	
	private static final int ACTIVITY_CREATE=0;
    private static final int ACTIVITY_EDIT=1;

    private static final int INSERT_ID = Menu.FIRST;
    private static final int DELETE_ID = Menu.FIRST + 1;
    private static final int EDIT_ID = Menu.FIRST + 2;
    private static final int COMPLETE_ID = Menu.FIRST + 3;
    
    private ToDoAppDbAdapter mDbHelper;
    
    /**
	 * onCreate method
	 * @param savedInstanceState
	 */
    @Override
    public void onCreate(Bundle savedInstanceState) {
    	Log.d("Category onCreate", "Beginning");
    	super.onCreate(savedInstanceState);
        setContentView(R.layout.items);
        
        //Gets the id of the category that was just clicked on and saves that id as categoryId
        if (savedInstanceState == null) {
            Bundle extras = getIntent().getExtras();
            
            if (extras != null) {
            	Log.d("Category onCreate", "create extras.size = " + extras.size());
            	if(extras.size() == 0) {
            		accountId = null;
            		categoryId = null;
            	}
             
	            else {
	            	accountId = extras.getString(ToDoAppDbAdapter.KEY_CATEGORY_ACCOUNTID);
	                Log.d("Category onCreate", "edit extras.size = " + extras.size());
	                if(extras.size() >= 2)
	                	categoryId = extras.getString(ToDoAppDbAdapter.KEY_CATEGORY_ROWID);
	                else
	                	categoryId = null;
	            }
            }
        }
        else {
        	accountId = (String) savedInstanceState.getSerializable(ToDoAppDbAdapter.KEY_CATEGORY_ACCOUNTID);       
            categoryId = (String) savedInstanceState.getSerializable(ToDoAppDbAdapter.KEY_CATEGORY_ROWID);            
        }
        Log.d("Category onCreate", "categoryId "+ categoryId);
        
        mDbHelper = new ToDoAppDbAdapter(this);
        mDbHelper.open();
        Log.d("Category onCreate", "Before fillData" + "categoryId" + categoryId);
        fillData();
        registerForContextMenu(getListView());
        
        Button filterButton = (Button) findViewById(R.id.filter);

    	filterButton.setOnClickListener(new View.OnClickListener() {

    		public void onClick(View view) {
    			
    			//Category.this reference to the current Category object that has been instantiated.
    			Intent i = new Intent(Category.this, Filter.class);
    			startActivityForResult(i,0);
    		}

    	});
        
        
        
    }
    
    /**
     * Constructs item list view for the user.
     */
    
    private void fillData() {
    	Log.d("Category fillData", "categoryId " + categoryId);
        Cursor itemsCursor;
        if(categoryId != null){
        	itemsCursor = mDbHelper.fetchAllItems(accountId, categoryId);
        	startManagingCursor(itemsCursor);
        }
        else{
        	itemsCursor = mDbHelper.fetchAllItems();
        	startManagingCursor(itemsCursor);
        }
        
        
        startManagingCursor(itemsCursor);

        String[] from = new String[]{ToDoAppDbAdapter.KEY_ITEM_TITLE};

        int[] to = new int[]{R.id.item1};

        SimpleCursorAdapter items = 
            new SimpleCursorAdapter(this, R.layout.items_row, itemsCursor, from, to);
        setListAdapter(items);
    }
    
/**
 * Retrieves a specific items complete String and reverses the state of complete.
 * @param id the id of the row to change
 */
    public void changeComplete(long id)
    {
    	Cursor itemCursor = mDbHelper.fetchItem(id);
        startManagingCursor(itemCursor);
        
        String complete = itemCursor.getString(5);
        Log.d("Category changeComplete", "complete " + complete);
        mDbHelper.updateComplete(id, complete);
    }

    /**
	 * Initialize the contents of the Activity's standard options menu.
	 * @param menu The options menu in which you place your items.
	 * @return return true for the menu to be displayed; if you return false it will not be shown.
	 */
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        super.onCreateOptionsMenu(menu);
        menu.add(0, INSERT_ID, 0, R.string.item_insert);
        return true;
    }

    /**
     * Default implementation of onMenuItemSelected(int, MenuItem) for activities
     * @param featureId The panel that the menu is in.
     * @param item The menu item that was selected.
     * @return boolean Return true to finish processing of selection, or false to perform the normal menu handling (calling its Runnable or sending a Message to its target Handler).
     */
    @Override
    public boolean onMenuItemSelected(int featureId, MenuItem item) {
        switch(item.getItemId()) {
            case INSERT_ID:
                createItem();
                return true;
        }

        return super.onMenuItemSelected(featureId, item);
    }

    /**
     * Called when a context menu for the view is about to be shown.
     * @param menu The context menu that is being built
     * @param v The view for which the context menu is being built
     * @param menuInfo Extra information about the item for which the context menu should be shown. This information will vary depending on the class of v.
     */
    @Override
    public void onCreateContextMenu(ContextMenu menu, View v,
            ContextMenuInfo menuInfo) {
        super.onCreateContextMenu(menu, v, menuInfo);
        menu.add(0, DELETE_ID, 0, R.string.item_delete);
        menu.add(0, EDIT_ID, 0, R.string.item_edit);
/**/        menu.add(0, COMPLETE_ID, 0, R.string.item_complete);
    }

    /**
     * This hook is called whenever an item in a context menu is selected.
     * @param item The context menu item that was selected.
     * @return boolean Return false to allow normal context menu processing to proceed, true to consume it here.
     */
    @Override
    public boolean onContextItemSelected(MenuItem item) {
    	AdapterContextMenuInfo info;
    	info = (AdapterContextMenuInfo) item.getMenuInfo();
        switch(item.getItemId()) {
            case DELETE_ID:
                mDbHelper.deleteItem(info.id);
                fillData();
                return true;
            case EDIT_ID:
                Intent i = new Intent(this, EditItem.class);
                Log.d("Category onContextItemSelected", "categoryId "+ categoryId);
                i.putExtra(ToDoAppDbAdapter.KEY_ITEM_ACCOUNTID, accountId);
                i.putExtra("categoryId", categoryId);
                i.putExtra(ToDoAppDbAdapter.KEY_ITEM_ROWID, info.id);
                startActivityForResult(i, ACTIVITY_EDIT);
                fillData();
                return true;
/**/            case COMPLETE_ID:
            	changeComplete(info.id);
                return true;
        }
        return super.onContextItemSelected(item);
    }

    /**
     * Starts a new activity to create new item.
     */
    
    private void createItem() {
        Intent i = new Intent(this, EditItem.class);
        i.putExtra(ToDoAppDbAdapter.KEY_ITEM_ACCOUNTID, accountId);
        i.putExtra("categoryId", categoryId);
        startActivityForResult(i, ACTIVITY_CREATE);
    }
    
    /**
     * This method will be called when an item in the list is selected.
     * @param l	The ListView where the click happened
     * @param v The view that was clicked within the ListView
     * @param position The position of the view in the list
     * @param id The row id of the item that was clicked
     */
    @Override
    protected void onListItemClick(ListView l, View v, int position, long id) {
    	setContentView(R.layout.items_view);
    	TextView title = (TextView) findViewById(R.id.title_view);
    	TextView description = (TextView) findViewById(R.id.description_view);
    	TextView location = (TextView) findViewById(R.id.location_view);
    	TextView duedate = (TextView) findViewById(R.id.duedate_view);
    	
    	Cursor itemCursor = mDbHelper.fetchItem(id);
    	Log.d("Category onListItemClicked", "title " + itemCursor.getString(1));
    	Log.d("Category onListItemClicked", "description " + itemCursor.getString(2));
    	Log.d("Category onListItemClicked", "location " + itemCursor.getString(3));
    	Log.d("Category onListItemClicked", "due date " + itemCursor.getString(4));
        title.setText(itemCursor.getString(1));
        description.setText(itemCursor.getString(2));
        location.setText(itemCursor.getString(3));
        duedate.setText(itemCursor.getString(4));
       
        if(itemCursor.getString(5).equals("true"))
        		title.setPaintFlags(title.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
    }

    /**
     * Called when an activity you launched exits, giving you the requestCode you started it with, 
     * the resultCode it returned, and any additional data from it.
     * @param requestCode The integer request code originally supplied to startActivityForResult(), allowing you to identify who this result came from.
     * @param resultCode The integer result code returned by the child activity through its setResult().
     * @param intent An Intent, which can return result data to the caller (various data can be attached to Intent "extras").
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
        super.onActivityResult(requestCode, resultCode, intent);
        fillData();
    }
}
